const sys = require(`./system.js`)
const $ = sys.$('助学权益盈亏')

sys.run($, 'task:one', (resList, cookie, index, username, password, item) => {
    return new Promise(async resolve => {
        // 请求接口
        const qInfo = $.localStorage.get('task:qInfo', 'localStorageInfo') || {}
        const dateStr = new Date().toLocaleDateString()
        let list = qInfo.list || []
        
        if(dateStr != qInfo.date) {
            const bidResp = await $.publicJS.bidList($, cookie)
            console.log('rows', bidResp.rows, list.length, bidResp.rows != list.length);
            if(bidResp.rows != list.length) {
                const pages = parseInt(bidResp.rows / 5) + 1
                // const pages = 10
                console.log('共计', pages);
                for (let page = 1; page <= pages; page++) {
                    list.push(...((await $.publicJS.bidList($, cookie, page)).data))
                }
            }
        }
        list = list.map(item => {
            return {
                id: item.id,
                equitiesId: item.equitiesId,
                '金额': item.amount || item['金额'],
                '购买时间': item.buyDate || item['购买时间'],
                '回款时间': item.collectionDate || item['回款时间'],
                '预计贴现时间': item.deadLine || item['预计贴现时间'],
                '预计收益': item.expectedEarnings || item['预计收益'],
                '实际收益': item.realEarnings || item['实际收益'],
                '用户': item.equities && item.equities.loanUserName || item['用户'],
                '机构': item.equities && item.equities.corporationName || item['机构'],
                // 'WG占用金额': item.equities.occupyDepositAmount || item['WG占用金额'],
                // 'WG服务金': item.equities.serviceCharge || item['WG服务金'],
                // 'WG服务比': item.equities.serviceChargeRate || item['WG服务比'],
            }
        })
        const infoMap = {}
        list = list.map(item => {
            const info = infoMap[item['机构']] = infoMap[item['机构']] || {
                '总': 0,
                '正常': 0,
                '退学': 0,
                '逾期': 0,
                '提前': 0,
            }
            info['总'] += 1
            let state = ''
            let cDay = ''
            const expectedEarnings = item['预计收益']
            const realEarnings = item['实际收益']
            const deadLine = new Date(item['预计贴现时间'].substring(0, 10))
            const collectionDate = new Date(item['回款时间'].substring(0, 10))
            const buyDate = new Date(item['购买时间'].substring(0, 10))
            
            const tDay = (collectionDate - buyDate) / 60 / 60 / 24 / 1000
            if(expectedEarnings != realEarnings) {
                info['退学'] += 1
                state = '退学🚩'
            } else if(deadLine > collectionDate) {
                info['提前'] += 1

                cDay = (deadLine - collectionDate) / 60 / 60 / 24 / 1000
                state = '提前💚'
            } else if(deadLine < collectionDate) {
                info['逾期'] += 1

                cDay = (collectionDate - deadLine) / 60 / 60 / 24 / 1000
                state = '逾期💔'
            } else {
                info['正常'] += 1
                state = '正常✅'
            }
            return {
                ...item,
                '状态': state,
                '提前OR逾期(天)': cDay,
                '持有(天)': tDay,
            }
        })

        Object.keys(infoMap).forEach(key => {
            const value = infoMap[key]
            const tq = value['提前']
            const yq = value['逾期']
            if(!tq) {
                value['比率'] = 0
            } else if (!yq) {
                value['比率'] = tq * 100
            } else {
                value['比率'] = Number((tq / yq * 100).toFixed(2))
            }
        });

        $.localStorage.set('task:qInfo-infoMap', infoMap, 'localStorageInfo')

        resList.push(
            ...list
        )
        resolve(resList)
    })
}, (resList) => {
    console.log('任务结束 resList:', resList)
    if (resList && resList.length > 0) {
        // resList = resList.sort((a1, a2) => {
        //     return a1['序号'] - a2['序号']
        // })
        $.localStorage.set('task:qInfo', {
            date: new Date().toLocaleDateString(),
            list: resList
        }, 'localStorageInfo')

        // 1. 
        // console.log(resList);
        // resList = resList.sort((a1, a2) => {
        //     return a2['账户全部资产'] - a1['账户全部资产']
        // })
        // $.localStorage.set('task:qInfo', resList, 'localStorageInfo')
    }
})
